<?php
/**
 * Description: 获取直播课播放地址
 * User: devforma
 * Date: 15/5/12
 * Time: 10:28
 */

require_once LIB_DIR . '/LiveCourse.class.php';
class OpenCourseUrl implements iController {

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $cmsdb, $uddb;

        if (validateUser($queryArgs) !== 1)
            return genOutput(1000);

        $userId = $queryArgs['user_id'];

        if (empty($queryArgs['course_id']) || !is_numeric($queryArgs['course_id']))
            return genOutput(1000);

        //验证该用户是否可见
//        if (!LiveCourse::isOpenCourseBooked($cmsdb, $userId, $queryArgs['course_id']))
//            return genOutput(1000);

//        $available = $cmsdb->getVar('SELECT `is_available` FROM `gray_user_open_course` WHERE `user_id`=:uid AND `course_id`=:cid',
//            array(':uid' => $userId, ':cid' => $queryArgs['course_id']));

//        if (empty($available))
//            return genOutput(1000);

        //获取课程信息
        $sql = 'SELECT c.id, c.room_id, c.live_platform, c.start_time, c.end_time FROM `data_live_class` AS c INNER JOIN `relationship_live_class_and_course` AS r ON
        c.id=r.class_id AND r.course_id=:course_id LIMIT 1';
        $course = $cmsdb->getRow($sql, array(':course_id' => $queryArgs['course_id']));

        if (empty($course) || empty($course->room_id)) {
            return genOutput(1001);
        }

        $uInfo = getUserInfo($userId); //获取用户信息
        if (empty($uInfo))
            return genOutput(1000);

        if (empty($uInfo->nickname))
            $uInfo->nickname = 'student_'.$userId;
        $uInfo->nickname .= '-天天模考App';

        //获取播放地址
        if ($course->live_platform === '多贝云') {
            $url = LiveCourse::GetLiveClassUrl($userId, $uInfo->nickname, $course->room_id, $course->live_platform == '多贝云');
        } elseif ($course->live_platform === '欢拓云') {
            $mtRoomid = $cmsdb->getVar('SELECT t.maituo_room_id FROM `data_teacher` AS t, `data_live_class` AS c WHERE t.id=c.lector_id AND c.id=:cid',
                array(':cid' => $course->id));

            if (empty($mtRoomid)) {
                return genOutput(1001);
            }

            $url = LiveCourse::GetHtClassUrl($course->id, $mtRoomid, $userId, $uInfo->nickname, strtotime($uInfo->end_time) < time());
        } else {
            return genOutput(1001);
        }

        //访问记录
        LiveCourse::logEnter($userId, $queryArgs['course_id'], $queryArgs['terminal_type'], $course->start_time);

        return genOutput(1, array(
            'url' => $url
        ));
    }
}